package com.example.security1.config.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.security1.config.jwt.JwtUtils;
import com.example.security1.config.redis.RedisService;
import com.example.security1.config.security.LoginResult;
import com.example.security1.web.user.entity.User;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component("loginSuccessHandler")
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtUtils jwtUtils;
    private final RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        // 用户信息
        User user = (User)authentication.getPrincipal();
        // 生成token
        String token = jwtUtils.generateToken(user);
        // 获取token过期时间
        Long expireTime = Jwts.parser()
                .setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(token)
                .getBody().getExpiration().getTime();
        // 组装返回数据
        LoginResult result = new LoginResult();
        result.setId(user.getUId());
        result.setToken(token);
        result.setExpireTime(expireTime);
        result.setCode(200);

        // 返回json
        String res = JSONObject.toJSONString(result, SerializerFeature.DisableCircularReferenceDetect);
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(res.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

        // 把生成的token存到redis
        String tokenKey = "token_" + token;
        redisService.set(tokenKey, token, jwtUtils.getExpiration() / 1000);
    }
}
